<template>
  <div>
    <el-row class="page_top">
      <el-col :span="6">
        <el-form :model="search">
          <el-form-item prop="customerName">
            <el-autocomplete
              :fetch-suggestions="querySearchAsync"
              placeholder="请输入客户姓名"
              @select="handleSelect"
              v-model="search.customerName"
              clearable
              @clear="cleanSearch"
              ref="elautocomplete"
            >
              <template slot-scope="{ item }">
                <span>{{ item.label }}</span>
                <span v-show="false">{{ item.value }}</span>
              </template>
              <template slot="append">
                <el-button slot="append" icon="el-icon-search" @click="searchAll"></el-button>
              </template>
            </el-autocomplete>
          </el-form-item>
        </el-form>
      </el-col>
      <el-col :span="18">
        <el-button type="primary" size="small" @click="add" class="btn_add">添加</el-button>
      </el-col>
    </el-row>

    <el-table :data="lists" border style="width: 100%">
      <el-table-column type="expand">
        <template slot-scope="props">
          <el-form label-position="left" inline class="customer_info">
            <el-form-item label="护照编号">
              <span>{{ props.row.PASSENGER_PASSPORT }}</span>
            </el-form-item>
            <el-form-item label="护照有效期">
              <span>{{ props.row.PASSENGER_VALID }}</span>
            </el-form-item>
            <el-form-item label="生日">
              <span>{{ props.row.PASSENGER_BIRTHDAY }}</span>
            </el-form-item>
            <el-form-item label="性别">
              <span>{{ props.row.PASSENGER_GENDER === 'M' ? '男' : '女' }}</span>
            </el-form-item>
            <el-form-item label="邮箱">
              <span>{{ props.row.PASSENGER_EMAIL }}</span>
            </el-form-item>
            <el-form-item label="联系方式1">
              <span>{{ props.row.PASSENGER_PHONE1 }}</span>
            </el-form-item>
            <el-form-item label="联系方式2">
              <span>{{ props.row.PASSENGER_PHONE2 }}</span>
            </el-form-item>
            <el-form-item label="城市">
              <span>{{ props.row.PASSENGER_CITY }}</span>
            </el-form-item>
            <el-form-item label="邮政编码">
              <span>{{ props.row.PASSENGER_POSTCODE }}</span>
            </el-form-item>
            <el-form-item label="地址">
              <span>{{ props.row.PASSENGER_ADDRESS }}</span>
            </el-form-item>
          </el-form>
        </template>
      </el-table-column>
      <el-table-column type="index" width="50" align="center" label="序号"></el-table-column>
      <el-table-column label="客户姓名">
        <template slot-scope="props">
          <span>{{ props.row.PASSENGER_LASTNAME + props.row.PASSENGER_FIRSTNAME }}</span>
        </template>
      </el-table-column>
      <el-table-column label="出发地" width="300">
        <template slot-scope="props">
          <span>{{ props.row.PASSENGER_FROM | cityName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="目的地" width="300">
        <template slot-scope="props">
          <span>{{ props.row.PASSENGER_TO | cityName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="日期" align="center" width="150">
        <template slot-scope="props">
          <span>{{ props.row.PASSENGER_DATE | filterTime }}</span>
        </template>
      </el-table-column>
      <el-table-column label="机票类型" align="center" width="150" prop="PASSENGER_CLASS"></el-table-column>
      <!-- 操作列 -->
      <el-table-column label="管理" fixed="right" align="center" width="150">
        <template slot-scope="props">
          <!-- 修改 -->
          <el-button size="mini" @click="edit(props.row)">修改</el-button>
          <!-- 删除 -->
          <el-button type="danger" size="mini" @click="del(props.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <div class="table-pageblock">
      <!-- current-page 当前页数  page-size 每页显示数 total 总页数-->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10,20,30,40,50]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </div>
    <!-- 弹窗 新增or修改 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogShow" fullscreen>
      <!-- 添加/修改表单 -->
      <el-form label-width="100px" ref="customer" :model="customer">
        <el-row>
          <el-col :span="12">
            <el-row>
              <el-col :span="24">
                <el-form-item label="出发地" prop="PASSENGER_FROM">
                  <el-input v-model="customer.PASSENGER_FROM"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="24">
                <el-form-item label="目的地" prop="PASSENGER_TO">
                  <el-input v-model="customer.PASSENGER_TO"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="日期" prop="PASSENGER_DATE">
                  <el-date-picker
                    v-model="customer.PASSENGER_DATE"
                    style="width:100%"
                    type="date"
                    placeholder="选择日期"
                  ></el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="机票类型" prop="PASSENGER_CLASS">
                  <el-select
                    v-model="customer.PASSENGER_CLASS"
                    style="width:100%"
                    placeholder="请选择"
                  >
                    <el-option label="默认舱" value="默认舱"></el-option>
                    <el-option label="经济舱" value="经济舱"></el-option>
                    <el-option label="公务舱" value="公务舱"></el-option>
                    <el-option label="头等舱" value="头等舱"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
          <el-col :span="12">
            <el-row>
              <el-col :span="12">
                <el-form-item label="姓氏" prop="PASSENGER_LASTNAME">
                  <el-input v-model="customer.PASSENGER_LASTNAME" placeholder="请输入大写拼音或字母"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="名字" prop="PASSENGER_FIRSTNAME">
                  <el-input v-model="customer.PASSENGER_FIRSTNAME" placeholder="请输入大写拼音或字母"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="护照编号" prop="PASSENGER_PASSPORT">
                  <el-input v-model="customer.PASSENGER_PASSPORT"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="护照有效期" prop="PASSENGER_VALID">
                  <el-date-picker
                    v-model="customer.PASSENGER_VALID"
                    style="width:100%"
                    type="date"
                    placeholder="选择日期"
                  ></el-date-picker>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="12">
                <el-form-item label="生日" prop="PASSENGER_BIRTHDAY">
                  <el-date-picker
                    v-model="customer.PASSENGER_BIRTHDAY"
                    style="width:100%"
                    type="date"
                    placeholder="选择日期"
                  ></el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="性别" prop="PASSENGER_GENDER">
                  <el-select
                    v-model="customer.PASSENGER_GENDER"
                    style="width:100%"
                    placeholder="请选择"
                  >
                    <el-option label="男" value="M"></el-option>
                    <el-option label="女" value="F"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="邮箱" prop="PASSENGER_EMAIL">
              <el-input v-model="customer.PASSENGER_EMAIL"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="手机" prop="PASSENGER_PHONE1">
              <el-input v-model="customer.PASSENGER_PHONE1"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="固定电话" prop="PASSENGER_PHONE2">
              <el-input v-model="customer.PASSENGER_PHONE2"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="城市" prop="PASSENGER_CITY">
              <el-input v-model="customer.PASSENGER_CITY"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="邮政编号" prop="PASSENGER_POSTCODE">
              <el-input v-model="customer.PASSENGER_POSTCODE"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="地址" prop="PASSENGER_ADDRESS">
              <el-input v-model="customer.PASSENGER_ADDRESS"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer">
        <el-button type="primary" size="small" v-if="dialogTitle === '添加'" @click="create">添加</el-button>
        <el-button size="small" v-else @click="update">修改</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { Component, Vue, Prop } from "vue-property-decorator";
import { get, post } from "@/http";
import { State, Action } from "vuex-class";
import code from "../../public/cityCode.json";
import { _debounce } from "../../public/debounce.js";
import moment from "moment";

// 组件定义
@Component({
  name: "Customerlist",
  filters: {
    filterTime: value => {
      return moment(value).format("YYYY-MM-DD");
    },
    cityName: value => {
      for (let i = code.cities.length; i--; ) {
        if (code.cities[i][4] === value) {
          return (
            code.cities[i][6] +
            code.cities[i][5] +
            code.cities[i][0] +
            "[" +
            code.cities[i][4] +
            "]"
          );
        } else {
          for (let j = code.cities[i][11].length; j--; ) {
            if (code.cities[i][11][j][2] === value) {
              return (
                code.cities[i][6] +
                code.cities[i][5] +
                code.cities[i][11][j][4] +
                "[" +
                code.cities[i][11][j][2] +
                "]"
              );
            }
          }
        }
      }
    }
  }
})
export default class Customerlist extends Vue {
  // 初始数据
  lists = [];

  // 查询条件
  search = {
    PASSENGER_PASSPORT: "",
    customerName: ""
  };

  // 远程搜索
  restaurants = [];
  // 计时器
  timeout = null;

  // 当前页
  currentPage = 1;
  // 当前数
  pageSize = 10;
  // 总条目数
  total = 20;

  // 弹窗标题
  dialogTitle = "";
  // 弹窗是否显示
  dialogShow = false;

  customer = {
    PASSENGER_FROM: "",
    PASSENGER_TO: "",
    PASSENGER_DATE: "",
    PASSENGER_CLASS: "",
    PASSENGER_LASTNAME: "",
    PASSENGER_FIRSTNAME: "",
    PASSENGER_PASSPORT: "",
    PASSENGER_VALID: "",
    PASSENGER_BIRTHDAY: "",
    PASSENGER_GENDER: "",
    PASSENGER_EMAIL: "",
    PASSENGER_PHONE1: "",
    PASSENGER_PHONE2: "",
    PASSENGER_ADDRESS: "",
    PASSENGER_CITY: "",
    PASSENGER_POSTCODE: ""
  };

  // 加载实例后执行
  mounted() {
    this.getCustomers();
    this.loadAll();
  }

  loadAll() {
    let list = [];
    let params = {
      mark: 0
    };
    post("/api/customer/getCustomerAll", params)
      .then(res => {
        if (res.success) {
          for (let i = res.data.length; i--; ) {
            list.push({
              value: res.data[i].PASSENGER_PASSPORT,
              label:
                res.data[i].PASSENGER_LASTNAME + res.data[i].PASSENGER_FIRSTNAME
            });
          }
          this.restaurants = list;
        } else {
          this.$message({
            message: res.message,
            type: "error"
          });
        }
      })
      .catch(err => {
        console.log(err);
      });
  }

  querySearchAsync(queryString, cb) {
    let _this = this;
    let restaurants = _this.restaurants;
    let results = queryString
      ? _this.createStateFilter(queryString)
      : restaurants;
    clearTimeout(_this.timeout);
    _this.timeout = setTimeout(() => {
      cb(results);
    }, 200 * Math.random());
  }

  createStateFilter(queryString) {
    let _this = this;
    // 匹配结果
    let restaurants = _this.restaurants;
    // 搜索条件
    let state = _this.search.customerName;
    // 输入值转换大写
    queryString = queryString.toUpperCase();
    let result = restaurants.filter(
      state => state.label.toUpperCase().indexOf(queryString) === 0
    );
    return result;
  }

  handleSelect(item) {
    let _this = this;
    _this.$nextTick(() => {
      _this.search.customerName = item.label;
      _this.search.PASSENGER_PASSPORT = item.value;
    });
  }

  cleanSearch() {
    let _this = this;
    _this.$nextTick(() => {
      _this.search.customerName = "";
      _this.search.PASSENGER_PASSPORT = "";
    });
  }

  // 根据选择条件查询
  searchAll() {
    let _this = this;
    let params = {
      PASSENGER_PASSPORT: _this.search.PASSENGER_PASSPORT === undefined  || null ? '' : _this.search.PASSENGER_PASSPORT,
      mark: 0,
      limit: _this.pageSize,
      offset: _this.currentPage
    };
    post("/api/customer/getCustomerlist", params)
      .then(res => {
        if (res.success) {
          _this.lists = res.data.rows;
          _this.total = res.data.count;
          // 解决删除当前页数据后仍留在那一页 不跳回上一页的bug
          if (!res.data.rows.length && _this.currentPage !== 1) {
            // 当前页减一
            _this.currentPage -= 1;
            // 调用自己
            _this.getCustomers();
          }
        } else {
          this.$message({
            message: res.message,
            type: "error"
          });
        }
      })
      .catch(err => {
        console.log(err);
      });
  }

  // 查询客户
  getCustomers() {
    let _this = this;
    let params = {
      PASSENGER_PASSPORT: _this.search.PASSENGER_PASSPORT === undefined  || null ? '' : _this.search.PASSENGER_PASSPORT,
      mark: 0,
      limit: _this.pageSize,
      offset: _this.currentPage
    };
    post("/api/customer/getCustomerlist", params)
      .then(res => {
        if (res.success) {
          _this.lists = res.data.rows;
          _this.total = res.data.count;
          // 解决删除当前页数据后仍留在那一页 不跳回上一页的bug
          if (!res.data.rows.length && _this.currentPage !== 1) {
            // 当前页减一
            _this.currentPage -= 1;
            // 调用自己
            _this.getCustomers();
          }
        } else {
          this.$message({
            message: res.message,
            type: "error"
          });
        }
      })
      .catch(err => {
        console.log(err);
      });
  }

  // 每页显示的条数改变
  handleSizeChange(val) {
    this.pageSize = val;
    // 调用刷新页面
    this.getCustomers();
  }

  // 当前页码
  handleCurrentChange(val) {
    this.currentPage = val;
    // 调用
    this.getCustomers();
  }

  // 显示编辑界面
  edit(row) {
    let _this = this;
    _this.dialogTitle = "修改";
    _this.dialogShow = true;
    row.PASSENGER_DATE =
      moment(row.PASSENGER_DATE).format("YYYY-MM-DD") === "Invalid date"
        ? ""
        : moment(row.PASSENGER_DATE).format("YYYY-MM-DD");
    _this.customer = Object.assign({}, row);
  }

  // 显示新增界面
  add() {
    let _this = this;
    _this.dialogTitle = "添加";
    _this.dialogShow = true;
    _this.customer = {
      PASSENGER_FROM: "",
      PASSENGER_TO: "",
      PASSENGER_DATE: "",
      PASSENGER_CLASS: "",
      PASSENGER_LASTNAME: "",
      PASSENGER_FIRSTNAME: "",
      PASSENGER_PASSPORT: "",
      PASSENGER_VALID: "",
      PASSENGER_BIRTHDAY: "",
      PASSENGER_GENDER: "",
      PASSENGER_EMAIL: "test123@qq.com",
      PASSENGER_PHONE1: "13720004895",
      PASSENGER_PHONE2: "12301230123",
      PASSENGER_ADDRESS: "Garden City Street",
      PASSENGER_CITY: "Amsterdam",
      PASSENGER_POSTCODE: "1071JA"
    };
  }

  // 新增
  create() {
    let _this = this;
    const cusbox = this.$refs["customer"];
    this.$nextTick(() => {
      cusbox.validate(valid => {
        if (valid) {
          let params = {
            PASSENGER_FROM: _this.customer.PASSENGER_FROM,
            PASSENGER_TO: _this.customer.PASSENGER_TO,
            PASSENGER_DATE: moment(_this.customer.PASSENGER_DATE).format(
              "YYYYMMDD"
            ),
            PASSENGER_CLASS: _this.customer.PASSENGER_CLASS,
            PASSENGER_LASTNAME: _this.customer.PASSENGER_LASTNAME.toUpperCase(),
            PASSENGER_FIRSTNAME: _this.customer.PASSENGER_FIRSTNAME.toUpperCase(),
            PASSENGER_PASSPORT: _this.customer.PASSENGER_PASSPORT,
            PASSENGER_VALID: moment(_this.customer.PASSENGER_VALID).format(
              "YYYY-MM-DD"
            ),
            PASSENGER_BIRTHDAY: moment(
              _this.customer.PASSENGER_BIRTHDAY
            ).format("YYYY-MM-DD"),
            PASSENGER_GENDER: _this.customer.PASSENGER_GENDER,
            PASSENGER_EMAIL: _this.customer.PASSENGER_EMAIL,
            PASSENGER_PHONE1: _this.customer.PASSENGER_PHONE1,
            PASSENGER_PHONE2: _this.customer.PASSENGER_PHONE2,
            PASSENGER_ADDRESS: _this.customer.PASSENGER_ADDRESS,
            PASSENGER_CITY: _this.customer.PASSENGER_CITY,
            PASSENGER_POSTCODE: _this.customer.PASSENGER_POSTCODE,
            mark: 0
          };
          post("api/customer/addCustomer", params)
            .then(res => {
              if (res.success) {
                this.$message({
                  message: res.message,
                  type: "success"
                });
                _this.dialogShow = false;
                _this.getCustomers();
                _this.loadAll();
              } else {
                this.$message({
                  message: res.message,
                  type: "error"
                });
              }
            })
            .catch(err => {
              console.log(err);
            });
        } else {
          return false;
        }
      });
    });
  }

  // 修改
  update() {
    let _this = this;
    const cusbox = this.$refs["customer"];
    this.$nextTick(() => {
      cusbox.validate(valid => {
        if (valid) {
          let params = {
            id: _this.customer.id,
            PASSENGER_FROM: _this.customer.PASSENGER_FROM,
            PASSENGER_TO: _this.customer.PASSENGER_TO,
            PASSENGER_DATE: moment(_this.customer.PASSENGER_DATE).format(
              "YYYYMMDD"
            ),
            PASSENGER_CLASS: _this.customer.PASSENGER_CLASS,
            PASSENGER_LASTNAME: _this.customer.PASSENGER_LASTNAME.toUpperCase(),
            PASSENGER_FIRSTNAME: _this.customer.PASSENGER_FIRSTNAME.toUpperCase(),
            PASSENGER_PASSPORT: _this.customer.PASSENGER_PASSPORT,
            PASSENGER_VALID: moment(_this.customer.PASSENGER_VALID).format(
              "YYYY-MM-DD"
            ),
            PASSENGER_BIRTHDAY: moment(
              _this.customer.PASSENGER_BIRTHDAY
            ).format("YYYY-MM-DD"),
            PASSENGER_GENDER: _this.customer.PASSENGER_GENDER,
            PASSENGER_EMAIL: _this.customer.PASSENGER_EMAIL,
            PASSENGER_PHONE1: _this.customer.PASSENGER_PHONE1,
            PASSENGER_PHONE2: _this.customer.PASSENGER_PHONE2,
            PASSENGER_ADDRESS: _this.customer.PASSENGER_ADDRESS,
            PASSENGER_CITY: _this.customer.PASSENGER_CITY,
            PASSENGER_POSTCODE: _this.customer.PASSENGER_POSTCODE
          };
          post("api/customer/updateCustomer", params)
            .then(res => {
              if (res.success) {
                this.$message({
                  message: res.message,
                  type: "success"
                });
                _this.dialogShow = false;
                _this.getCustomers();
                _this.loadAll();
              } else {
                this.$message({
                  message: res.message,
                  type: "error"
                });
              }
            })
            .catch(err => {
              console.log(err);
            });
        } else {
          return false;
        }
      });
    });
  }

  // 删除客户
  del(row) {
    let _this = this;
    let params = {
      id: row.id,
      mark: 1
    };
    // 删除二次确认
    _this
      .$confirm("确认删除选中的信息吗？", "提示", {
        type: "warning"
      })
      .then(() => {
        post("/api/customer/delCustomer", params)
          .then(res => {
            if (res.success) {
              this.$message({
                message: "删除成功！",
                type: "success"
              });
              _this.getCustomers();
              _this.loadAll();
            }
          })
          .catch(err => {
            console.log(err);
          });
      })
      .catch(() => {
        _this.$message({
          type: "info",
          message: "已取消删除"
        });
      });
  }
}
</script>

<style lang="scss">
.page_top {
  padding: 15px;
  .el-form-item {
    margin-bottom: 0;
  }
  .btn_add {
    margin: 5px 0;
    float: right;
  }
}
.customer_info {
  font-size: 0;

  .el-form-item {
    margin-right: 0;
    margin-bottom: 0;
    width: 100%;
    padding: 0;
    margin: 0;
  }
}

.el-dialog {
  .el-dialog__header {
    padding: 20px;
    .el-dialog__title {
      font-size: 16px;
    }
  }

  .el-dialog__body {
    padding: 0 15px;
  }
  .el-dialog__footer {
    padding-top: 0;
  }
}
</style>
